﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Common;
using UsefulCode;

namespace FlashcardWeb.Controllers
{
    public class ServiceController : Controller
    {
        //
        // GET: /Service/
		
        public ActionResult Pronunciation(string value)
        {
			//var words =  value.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x=> x.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries));

			var valueWords = from word in value.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
						select new { Word = word, Words = word.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) };

			var words = (from word in valueWords
						 from k in word.Words
						 select k).Distinct();

			var w = string.Join(",", words.Select(x=> string.Format("'{0}'", x))); 
			
			string result = string.Empty;

			Dictionary<string, string> dic = new Dictionary<string, string>();

			try
			{
				Action<DbCommand> action = (command) =>
				{


					command.CommandText = string.Format("SELECT Word, BrE, AmE FROM Words where Word IN({0})", w);

					using (DbDataReader reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							dic.Add(reader.GetString(0), reader.GetString(1));
						}
					}

				};
								
				Db.Work("pronunciation", action);
							
				var xxx = from cx in valueWords
						  select string.Join(" ", cx.Words.Select(x=> dic[x]));


				return Json(xxx, JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(ex.Message, JsonRequestBehavior.AllowGet);
			}
        }

    }
}
